from contextlib import contextmanager
from typing import Optional

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from sqlalchemy.orm import scoped_session

from common.models import MetaData, Base

db = SQLAlchemy(metadata=MetaData)
migrate = Migrate(db=db)

_app: Optional[Flask] = None


def init_db_app(app):
    global _app
    _app = app

    db.init_app(app)
    migrate.init_app(app)
    Base.query = db.session.query_property()


@contextmanager
def session_scope() -> scoped_session:
    if not _app:
        raise ValueError('db is not init.')

    with _app.app_context():
        try:
            yield db.session
            db.session.commit()
        finally:
            db.session.close()
